package handlers

import (
	"encoding/json"
	"log"

	"github.com/SiriusScan/go-api/sirius"
	"github.com/SiriusScan/go-api/sirius/vulnerability"
	"github.com/gofiber/fiber/v2"
)

//* The API exposes functions from the go-api/sirius/vulnerability package to JSON endpoints
//* GetVulnerability handles the GET /vulnerability/{id} route
// It retrieves a CVEItem from the database and returns it as JSON

func GetVulnerability(c *fiber.Ctx) error {
	vid := c.Params("id")
	// log.Println("Getting vulnerability with ID:", vid)

	// Retrieve svdb data with the GetVulnerability function from the sirius.vulnerability package
	vulnData, err := vulnerability.GetVulnerability(vid)

	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": err.Error(),
		})
	}

	// Return the vulnerability data as JSON
	return c.JSON(vulnData)
}

func AddVulnerability(c *fiber.Ctx) error {
	// Read the raw request body
	requestBody := string(c.Body())

	// Define a local struct that matches the expected JSON structure
	var newVuln sirius.Vulnerability

	// Manually unmarshal JSON into the struct
	err := json.Unmarshal([]byte(requestBody), &newVuln)
	if err != nil {
		log.Println("Error parsing request body:", err.Error())
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "Error parsing request body: " + err.Error(),
		})
	}

	log.Println("Adding vulnerability with ID: " + newVuln.VID)
	// log.Println(newVuln)

	// Add the vulnerability to the database
	err = vulnerability.AddVulnerability(newVuln)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": err.Error(),
		})
	}

	// Return the vulnerability data as JSON
	return c.JSON(newVuln)
}

func DeleteVulnerability(c *fiber.Ctx) error {
	// Read the raw request body
	requestBody := string(c.Body())

	// Define a local struct that matches the expected JSON structure
	type Req struct {
		VID string `json:"vid"`
	}
	var newVuln Req

	// Manually unmarshal JSON into the struct
	err := json.Unmarshal([]byte(requestBody), &newVuln)
	if err != nil {
		log.Println("Error parsing request body:", err.Error())
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "Error parsing request body: " + err.Error(),
		})
	}

	// Delete the vulnerability from the database
	err = vulnerability.DeleteVulnerability(newVuln.VID)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": err.Error(),
		})
	}

	return c.JSON(fiber.Map{
		"message": "Vulnerability deleted successfully",
	})
}
